package com.washmadam.service.service.manager.impl;

import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.washmadam.service.common.constants.Constant;
import com.washmadam.service.common.enums.DeleteEnum;
import com.washmadam.service.db.dao.ManagerMapper;
import com.washmadam.service.db.dto.Manager;
import com.washmadam.service.db.example.ManagerExample;
import com.washmadam.service.db.response.ManagerResponse;
import com.washmadam.service.service.manager.ManagerService;

import common.service.base.common.MobileSession;
import common.service.base.common.SessionInfo;
import common.service.contants.MobileConfig;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ManagerServiceImpl implements ManagerService {

	@Autowired
	private MobileSession mobileSession;
	@Autowired
	private ManagerMapper managerMapper;
	@Override
	public Manager queryManagerDetail(Manager manager) {
		if(manager ==null) {
			throw new RuntimeException("请输入手机号和密码");
		}
		if(StringUtils.isBlank(manager.getPhone())) {
			throw new RuntimeException("请输入手机号");
		}
		if(StringUtils.isBlank(manager.getPassword())) {
			throw new RuntimeException("请输入密码");
		}
		String password = DigestUtils.md5Hex(manager.getPassword() + Base64.encodeBase64String(Constant.LOGIN_SALT.getBytes()));
		ManagerExample example = new ManagerExample();
		example.createCriteria()
			   .andPhoneEqualTo(manager.getPhone())
			   .andPasswordEqualTo(password)
			   .andIsDeleteEqualTo(DeleteEnum.NORMAL.getCode());
		example.setOrderByClause("id desc");
		List<Manager> managerList = managerMapper.selectByExample(example);
		if(CollectionUtils.isEmpty(managerList)) {
			throw new RuntimeException("用户不存在");
		}
		Manager result =managerList.get(0);
		if(result.getStatus() !=1) {
			throw new RuntimeException("该用户已被禁用，请联系管理员");
		}
		return generateSessionInfo(result);
	}
	private ManagerResponse generateSessionInfo(Manager manager) {
		ManagerResponse response = new ManagerResponse();
		BeanUtils.copyProperties(manager, response);
        //生成token 创建会话
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fmDate = simpleDateFormat.format(manager.getCreateTime());
        String sessionId = mobileSession.createSession(manager.getId());// 设置过期时间为2小时
        SessionInfo sessionInfo = new SessionInfo(manager.getId(), manager.getName(),null, manager.getPhone(), fmDate);
        //session中缓存用户信息
        mobileSession.setAttribute(MobileConfig.SESSION_USR_INFO, sessionInfo,30*24*60*60);
        response.setToken(sessionId);
        return response;
    }
}
